package com.hbnu.system.controller;

import com.hbnu.system.core.base.Rest;
import com.hbnu.system.model.dto.LoginDTO;
import com.hbnu.system.model.vo.InfoVO;
import com.hbnu.system.service.IUserService;
import com.hbnu.system.utils.JwtUtils;
import com.hbnu.system.utils.MD5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/login")
@Api(tags = "登入模块")
public class LoginController {

    @Autowired
    private IUserService iUserService;


    @ApiOperation("登入")
    @PostMapping("/login")
    public Rest<Map<String, String>> login(@RequestBody LoginDTO loginDTO) {
        String encryptedPassword = MD5Util.encrypt(loginDTO.getPassword());
        loginDTO.setPassword(encryptedPassword);

        // 传入加密后的密码与数据库中的加密密码进行比对
        String token = iUserService.loginUser(loginDTO);
        Map<String, String> result = new HashMap<>();
        result.put("token", token);
        return Rest.success(result);
    }

    @ApiOperation("验证token")
    @GetMapping("/checktoken")
    public Rest<Boolean> checktoken(HttpServletRequest request){
        Boolean isValid = JwtUtils.checkToken(request.getHeader("token"));
        return isValid ? Rest.success() : Rest.failed();
    }

    @ApiOperation("返回Token获取信息")
    @GetMapping("/getInfo")
    public Rest<InfoVO> getInfo(String token) throws InstantiationException, IllegalAccessException {
        InfoVO info = iUserService.getInfo(token);
        return Rest.success(info);
    }

    @ApiOperation("退出登陆")
    @GetMapping("/logout")
    public Rest<Boolean> logout(HttpServletRequest request) throws InstantiationException, IllegalAccessException {
        // 清除本地会话
        request.getSession().invalidate();

        String token = request.getHeader("token");
        Boolean isSuccess = JwtUtils.maketoken(token);
        return isSuccess ? Rest.success() : Rest.failed();
    }
}
